package p0;

import java.util.*;

/**
 * @author pengjz <br>
 * @version <br>
 * @name Leetcode_14 <br>
 * @date 2020/5/30 0:42<br>
 */
public class Leetcode_19 {
    /**
     * Definition for singly-linked list.
     **/
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 用map缓存第几个node是谁
        ListNode temp = head;
        Map<Integer, ListNode> m = new HashMap<>();
        int index = 1;
        while (temp != null) {
            m.put(index++, temp);
            temp = temp.next;
        }
        int size = m.size();
        if (size == 1) {
            return null;
        }
        if (n == 1) {
            m.get(size - 1).next = null;
        } else if (n == size) {
            assert head != null;
            head = head.next;
        } else {
            m.get(size - n).next = m.get(size - n + 2);
        }
        return head;
    }

    public static void main(String[] args) {
        Leetcode_19 leetcode = new Leetcode_19();
        System.out.println(leetcode.removeNthFromEnd(null, 0));
    }
}
